package com.tanhua.dubbo.service.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.enums.MessageState;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.service.enums.CommentType;
import com.tanhua.dubbo.service.enums.IdType;
import com.tanhua.dubbo.service.service.IdService;
import com.tanhua.dubbo.service.service.TimeLineService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Don
 */
@Service(version = "1.0.0", interfaceClass = QuanZiApi.class)
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {


    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    private String getCommentUserLikeRedisKeyPrefix(Long id) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + id;
    }

    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLoveRedisKeyPrefix(Long id) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + id;
    }

    @Autowired
    private VideoApi videoApi;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private MessageApiImpl messageApi;

    /**
     * 查询好友动态
     * 1.查询登录用户的时间线表,获取动态id
     * 2.根据动态id查询动态表
     *
     * @param id       用户id
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Publish> queryPublishList(Long id, Integer page, Integer pagesize) {
        // 查询时间线表
        List<TimeLine> timeLineList = mongoTemplate.findAll(TimeLine.class, "quanzi_time_line_" + id);
        // 遍历时间线对象集合 存入动态id
        ArrayList<Object> publishIdList = new ArrayList<>();

        for (TimeLine timeLine : timeLineList) {
            publishIdList.add(timeLine.getPublishId());
        }
        // 根据动态id分页从动态表查询好友动态
        PageRequest pageRequest = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("created")));

        //获取已通过publishid集合
        List<ObjectId> collect = getPassPublishId(publishIdList);
        Query query = new Query(Criteria.where("id").in(collect)).with(pageRequest);
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);

        return publishList;
    }

    //筛选已通过审核的动态
    private List<ObjectId> getPassPublishId(ArrayList<Object> publishIdList) {
        List<Message> messageList = mongoTemplate.find(Query.query(Criteria.where("publishId").in(publishIdList).and("messageState").is("4")), Message.class);
        List<ObjectId> collect = messageList.stream().map(Message::getPublishId).collect(Collectors.toList());
        return collect;
    }

    /**
     * 查询推荐动态
     * 1.根据登录用户查询redis,获取推荐动态的pid
     * 2.根据pid从动态表中查询所有动态
     *
     * @param id       用户id
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Publish> queryRecommendPublishList(Long id, Integer page, Integer pagesize) {
        // 根据用户id从redis中获取所有动态pid字符串
        String redisKey = "QUANZI_PUBLISH_RECOMMEND_" + id;
        String data = redisTemplate.opsForValue().get(redisKey);

        if (!StringUtils.isNotBlank(data)) {
            return null;
        }
        // 切割pid字符串,存入集合
        ArrayList<Long> list = new ArrayList<>();
        String[] split = data.split(",");

        for (String s : split) {
            list.add(Long.valueOf(s));
        }
        // 根据pid从动态表分页查询推荐动态
        PageRequest pageRequest = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("pid").in(list)).with(pageRequest);
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);

        return publishList;
    }

    /**
     * 发布动态
     * 1.校验publish对象
     * 2.设置pid
     * 3.存入mongodb的publish表
     * 4.创建相册表对象 设置属性 写入相册表
     * 5.写入好友的时间线表(异步)
     *
     * @param publish 动态对象
     * @return
     */
    @Override
    public String savePublish(Publish publish) {
        // 校验publish 对象
        if (!ObjectUtil.isAllNotEmpty(publish.getText(), publish.getUserId())) {
            // 发布动态失败
            return null;
        }

        // 设置主键
        publish.setId(ObjectId.get());

        try {
            // 设置自增pid
            publish.setPid(idService.createId(IdType.PUBLISH));
            publish.setCreated(System.currentTimeMillis());

            // 写入publish表中
            mongoTemplate.save(publish);

            // 写入相册表
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setPublishId(publish.getId());
            album.setCreated(System.currentTimeMillis());
            mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

            // 写入好友的时间线表 (异步写入)
            timeLineService.saveTimeLine(publish.getUserId(), publish.getId());

            //加入messagestate状态
            Message message = new Message();
            message.setId(ObjectId.get());
            message.setMessageState(MessageState.UNDO.getState());
            message.setPublishId(publish.getId());
            message.setCreateDate(publish.getCreated());
            message.setCommentCount(Convert.toInt(queryCommentCount(ObjectUtil.toString(publish.getId()))));
            message.setLikeCount(Convert.toInt(queryLikeCount(ObjectUtil.toString(publish.getId()))));
            mongoTemplate.save(message);
        } catch (Exception e) {
            //TODO 需要做事务的回滚，Mongodb的单节点服务，不支持事务，对于回滚我们暂时不实现了
            log.error("发布动态失败~ publish =" + publish, e);
        }
        return publish.getId().toHexString();

    }

    /**
     * 发布评论
     *
     * @param id          用户id
     * @param publishId   动态/小视频 id
     * @param commentType 评论类型 (点赞 喜欢 文本)
     * @param content     评论内容
     * @return
     */
    private Boolean saveComment(Long id, String publishId, CommentType commentType, String content) {
        try {
            // 封装评论对象
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setUserId(id);
            comment.setPublishId(new ObjectId(publishId));
            comment.setCommentType(commentType.getType());
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());
            // 根据id查询动态
            Publish publish = queryPublishById(publishId);
            // 其他评论对象
            if (ObjectUtil.isNotEmpty(publish)) {
                comment.setPublishUserId(publish.getUserId());
            } else {
                // 根据id查询评论
                Comment myComment = queryCommentById(publishId);
                if (ObjectUtil.isNotEmpty(myComment)) {
                    comment.setPublishUserId(myComment.getUserId());
                } else {
                    // 其他情况，比如小视频等
                    //查询小视频
                    Video video = videoApi.queryVideoById(publishId);
                    if (ObjectUtil.isNotEmpty(video)) {
                        comment.setPublishUserId(video.getUserId());
                    } else {
                        // 其他情况，直接返回
                        return false;
                    }
                }
            }

            mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + id + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }
        return false;
    }

    /**
     * 根据id查询评论
     *
     * @param publishId
     * @return
     */
    private Comment queryCommentById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId), Comment.class);
    }

    /**
     * 根据id查询动态
     *
     * @param id
     * @return
     */
    @Override
    public Publish queryPublishById(String id) {
        return mongoTemplate.findById(id, Publish.class);
    }

    /**
     * 查询点赞数
     *
     * @param publishId 动态/评论/视频 id
     * @return
     */
    @Override
    public Long queryLikeCount(String publishId) {
        // 从redis中命中查询
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();

        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return Convert.toLong(data);
        }
        // 查询mongodb
        Long count = queryCommentCount(publishId, CommentType.LIKE);

        //TODO 将点赞数更新到message_status表里

        // 写入redis
        redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));

        return count;
    }

    @Override
    public Long queryLoveCount(String publishId) {
        // 从redis中命中查询
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();

        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return Convert.toLong(data);
        }
        // 查询mongodb
        Long count = queryCommentCount(publishId, CommentType.LOVE);
        // 写入redis
        redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(data));

        return count;
    }

    /**
     * 点赞
     * 1.判断用户是否点赞 -- 已点赞 返回false
     * 2.调用保存动态方法 保存点赞的评论操作
     * 3.修改redis中点赞的状态和点赞数
     *
     * @param id        登录用户id
     * @param publishId 动态/评论/小视频id
     * @return
     */
    @Override
    public Boolean likeComment(Long id, String publishId) {
        // 判断用户是否已点赞
        Boolean isLike = queryUserIsLike(id, publishId);
        // 已点赞 失败
        if (isLike) {
            return false;
        }
        // 保存评论数据
        Boolean result = saveComment(id, publishId, CommentType.LIKE, null);
        // 保存失败 点赞失败
        if (!result) {
            return false;
        }
        // 点赞成功 修改redis中的点赞数 以及 是否点赞
        // 修改redis中的点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        // 修改用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(id);
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    /**
     * 取消点赞
     * 1.判断是否点赞
     * 2.根据登录用户id,publishId,评论类型 删除点赞的评论数据
     * 3.修改redis中点赞数和点赞状态
     *
     * @param id
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLikeComment(Long id, String publishId) {
        // 判断用户是否点赞
        Boolean isLike = queryUserIsLike(id, publishId);
        if (!isLike) {
            return false;
        }
        // 取消点赞
        Boolean result = removeComment(id, publishId, CommentType.LIKE);

        if (!result) {
            return false;
        }
        // 取消点赞成功 修改redis中的点赞数 以及 是否点赞
        // 修改redis中的点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        // 修改用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(id);
        redisTemplate.opsForHash().delete(redisKey, userHashKey);
        return true;
    }

    @Override
    public Boolean loveComment(Long id, String publishId) {
        // 判断是否已经喜欢该动态
        Boolean isLove = queryUserIsLove(id, publishId);
        if (isLove) {
            return false;
        }
        // 喜欢
        Boolean result = saveComment(id, publishId, CommentType.LOVE, null);
        if (!result) {
            return false;
        }
        // 喜欢成功后 修改redis中的总喜欢数 是否喜欢
        // 修改总喜欢数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
        // 修改是否喜欢
        String userHashKey = getCommentUserLoveRedisKeyPrefix(id);
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    @Override
    public Boolean disLoveComment(Long id, String publishId) {
        // 判断用户是否喜欢
        Boolean isLove = queryUserIsLove(id, publishId);
        if (!isLove) {
            return false;
        }
        // 取消喜欢
        Boolean result = removeComment(id, publishId, CommentType.LOVE);
        if (!result) {
            return false;
        }
        // 取消喜欢成功后 修改redis中的总喜欢数 是否喜欢
        // 修改总喜欢数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, -1);
        //修改是否喜欢
        String userHashKey = getCommentUserLoveRedisKeyPrefix(id);
        redisTemplate.opsForHash().delete(redisKey, userHashKey);

        return true;
    }

    /**
     * 判断用户是否已经点赞
     * 1.通过传入的登录用户id和动态id 查询redis 得到用户点赞状态(1,0)
     * 2.点赞 返回true
     * 3.未点赞 查询mongodb的评论表
     * 4.未点赞 返回false
     * 5.已点赞 修改redis中点赞状态 返回true
     *
     * @param id
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLike(Long id, String publishId) {
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String userHashKey = getCommentUserLikeRedisKeyPrefix(id);
        // 查询redis
        Object data = redisTemplate.opsForHash().get(redisKey, userHashKey);
        // data不为空 且值为"1"
        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "1");
        }
        // 查询mongodb
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(id)
                .and("commentType").is(CommentType.LIKE));
        long count = mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }
        // 写入redis
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
        return true;
    }

    @Override
    public Boolean queryUserIsLove(Long id, String publishId) {
        // 查询redis
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String userHashKey = getCommentUserLoveRedisKeyPrefix(id);
        // data不为空 且值为"1"
        Object data = redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "1");
        }
        // 查询mongodb
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(id)
                .and("commentType").is(CommentType.LOVE.getType()));

        long count = mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }
        // 写入redis
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
        return true;
    }

    @Override
    public List<Comment> queryCommentsList(String publishId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("created")));

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        return commentList;
    }

    @Override
    public List<Comment> queryCommentsList(String publishId, Integer page, Integer pageSize, String sortProp, String sortOrder) {

        PageRequest pageRequest = null;
        if (StrUtil.equals("ascending", sortOrder)) {
            pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc(sortProp)));
        } else {
            pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc(sortProp)));
        }


        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        return commentList;
    }

    @Override
    public Long queryCommentCount(String publishId) {
        // 从redis中命中查询
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.COMMENT.toString();

        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);

        if (ObjectUtil.isNotEmpty(data)) {
            return Convert.toLong(data);
        }

        // 查询mongodb
        Long count = queryCommentCount(publishId, CommentType.COMMENT);

        // 写入redis
        redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));
        return count;
    }

    @Override
    public Boolean saveComment(Long id, String publishId, String content) {
        return saveComment(id, publishId, CommentType.COMMENT, content);
    }

    @Override
    public List<Comment> queryLikeCommentList(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.LIKE, page, pageSize);
    }

    @Override
    public List<Comment> queryUserCommentList(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.COMMENT, page, pageSize);
    }

    @Override
    public List<Comment> queryLoveCommentList(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.LOVE, page, pageSize);
    }

    @Override
    public List<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        List<Publish> publishList1 = messageApi.filterPublish(publishList);
        return publishList1;
    }

    private List<Comment> queryCommentListByUser(Long userId, CommentType commentType, Integer page, Integer pageSize) {

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));

        Query query = Query.query(Criteria.where("publishUserId").is(userId)
                .and("commentType").is(commentType.getType())).with(pageRequest);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        return commentList;
    }


    private Boolean removeComment(Long id, String publishId, CommentType commentType) {

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(id)
                .and("commentType").is(commentType.getType()));
        return mongoTemplate.remove(query, Comment.class).getDeletedCount() > 0;
    }

    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType()));
        return mongoTemplate.count(query, Comment.class);
    }

}
